var htmlRoot = document.querySelector("html");
var ulTodoList = document.querySelector("ul.toDoList");
var input = document.querySelector("input#todo");

function finishTodoItem() {
    //this 就是触发事件的元素（就是用户点击的元素）
    var id = this.dataset.id;
    var url = "/finish?id=" + id;
    var xhr = new XMLHttpRequest();
    var self = this;
    xhr.open("get",url);
    xhr.send();
    xhr.onload = function () {
        self.classList.add("finish");
        self.onclick = null;
    }
}

function appendTodo(todo) {
    var todoLi = document.createElement("li");
    todoLi.innerText = todo.todo;
    if(todo.state == true){
        todoLi.classList.add("finish");
    }else{
        todoLi.onclick = finishTodoItem;
        todoLi.dataset.id = todo.id;
    }
    ulTodoList.appendChild(todoLi);
}

//为"submit"按钮绑定save函数
function save() {
    var todoInput = input.value;
    var url = "/save?todo=" + encodeURI(todoInput);
    var xhr = new XMLHttpRequest();
    function success() {
        var todo = {
            "id":parseInt(xhr.responseText),
            "todo":todoInput,
            "state":0,
        };

        appendTodo(todo);
    }
    xhr.onload = success;
    xhr.open("get",url);
    xhr.send();
}
var submitBtn = document.querySelector(".button");
submitBtn.onclick =  save;

//页面加载完成之后，请求列表资源
function LoadTodoList() {
    var xhr = new XMLHttpRequest();
    function success() {
        if (xhr.status != 200){
            htmlRoot.innerHTML = xhr.responseText;
            return;
        }

        //1、JS进行JSON的反序列化
        var todoList = JSON.parse(xhr.responseText);
        //遍历每一项，添加到DOM树中
        for (var todo of todoList){
            appendTodo(todo);
        }
    }
    xhr.onload = success;
    xhr.open("get","/list");
    xhr.send();
}
LoadTodoList();

//点击未完成项时，请求完成资源